from rest_framework.views import APIView
from rest_framework.response import Response

from apps.base import models
from utils import return_code, jwt_token
from apps.base.serializers.account import AuthSerializer


class AuthView(APIView):
    # 如果全局设置认证组件，不走认证组件
    authentication_classes = []
    # 如果全局设置权限组件，不走权限组件
    permission_classes = []

    def post(self, request, *args, **kwargs):
        # 1.获取用户请求发送的用户名 & 密码

        # 2.数据校验
        serializer = AuthSerializer(data=request.data)
        if not serializer.is_valid():
            # detail: serializer.errors={username: ['错误', ...], password: ['错误', ...]}
            return Response({'code': return_code.FIELD_ERROR, 'detail': serializer.errors})

        # 3.数据库校验
        username = serializer.validated_data.get('username')
        password = serializer.validated_data.get('password')
        user_obj = models.UserInfo.objects.filter(username=username, password=password).first()
        if not user_obj:
            return Response({'code': return_code.VALIDATE_ERROR, 'detail': '用户名或密码错误'})

        # 4.生成jwt token返回
        token = jwt_token.get_jwt_token(user_obj, seconds=30)


        return Response({'code': return_code.SUCCESS, 'data': {'token': token, 'username': user_obj.username}})


class TestView(APIView):

    def get(self, request, *args, **kwargs):
        return Response('test')
